<?php
/*
 * (C) Copyright 2013 Torsten Gorath (http://www.blauesdach.de/).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *     Torsten Gorath
 */
require_once $basedir . "/inc/user.php";
class PrivilededUser extends User {
    
    private $roles;
    
    public function __construct($id="") {
        parent::__construct($id="");
        if($this->getEmail() != "") {
            initRoles();
        }
    }
    
    protected function initRoles() {
        global $VEREIN;
        $this->roles = array();
        $query = "SELECT t1.id, t2.role_name FORM " . $VEREIN['prefix']. "user_role AS t1";
        $query .= " JOIN roles AS t2 ON t1.role_id=t2.id";
        $query .= " WHERE t1.user_id='".$this->getEMail()."'";
        $roles = Database::getDefault()->execute($query);
        for($i = 0; $i < count($roles); $i++) {
            $this->roles[$roles[$i]['role_name']] = Role::getRolePerms($roles[$i['id']]);
        }
    }
    
    public function hasPrivilege($perm) {
        foreach($this->roles as $role) {
            if($role->hasPerm($perm)) {
                return true;
            }
        }
        return false;
    }
    
    public function hasRole($role_name) {
        return isset($this->roles[$role_name]);
    }
    
    public static function insertPerm($role_id, $perm_id) {
        $assoc = array('role_id'=>$role_id, 'perm_id'=>$perm_id);
        Database::getDefault()->insert('role_perm', $assoc);
    }
    
    public static function deletePerms() {
        $query = "TRUNCATE role_perm";
        return Database::getDefault()->executePerpare($query);
    }
}
?>